/**
 * 
 */
package org.t2.game.server.module.rank.api;

import java.util.ArrayList;
import java.util.List;

import org.gaming.service.asserts.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.t2.game.server.module.player.model.Player;
import org.t2.game.server.module.player.service.PlayerService;
import org.t2.game.server.module.rank.constant.RankType;
import org.t2.game.server.module.rank.model.Ranker;
import org.t2.game.server.module.rank.service.RankerContext;
import org.t2.game.server.module.rank.service.RankerService;
import org.t2.game.server.module.tips.TipsCode;

import sh.t2.share.apiutil.GameApi;
import sh.t2.share.module.rank.RankApiProtocol.RankQueryRequest;
import sh.t2.share.module.rank.RankApiProtocol.RankQueryResponse;
import sh.t2.share.module.rank.RankWebData;

/**
 * 
 */
@Controller
public class RankApi {

	@Autowired
	private RankerService rankerService;
	@Autowired
	private PlayerService playerService;

	@RequestMapping(value = GameApi.rankInfo)
	@ResponseBody
	public RankQueryResponse info(@RequestBody RankQueryRequest request) {
		RankType rankType = RankType.valueOf(request.rankType);
		Asserts.isTrue(rankType != null, TipsCode.RANK_TYPE_ERROR);

		RankerContext rankerContext = rankerService.getContext(rankType);

		List<RankWebData> rankers = new ArrayList<>();
		if (request.playerId > 0) {
			Ranker ranker = rankerContext.getRanker(request.playerId);
			Asserts.isTrue(ranker != null, TipsCode.PLAYER_NOT_FOUND);
			
			int rank = rankerContext.getRank(request.playerId);
			rankers.add(formRanker(ranker, rank));
		} else {
			int rank = 1;
			for (Ranker ranker : rankerContext.getAll()) {
				rankers.add(formRanker(ranker, rank));
				rank += 1;
			}
		}

		RankQueryResponse response = new RankQueryResponse();
		response.rankType = request.rankType;
		response.datas.addAll(rankers);
		return response;
	}

	public RankWebData formRanker(Ranker ranker, int rank) {
		Player player = playerService.getEntity(ranker.getPlayerId());
		RankWebData data = new RankWebData();
		data.rank = rank;
		data.playerId = ranker.getPlayerId();
		data.nick = player.getNick();
		data.score = ranker.getScore();
		data.subScore = ranker.getSubScore();
		data.time = ranker.getTime();
		return data;
	}
}
